#include <iostream>
#include <string>
#include <time.h>
#include "sock.hpp"
#include "protocol.hpp"

static void Usage(std::string proc)
{
    std::cout << "\nUsage:" << proc << "ip port" << std::endl;
}

int main(int args, char *argv[])
{
    srand((unsigned)time(nullptr) ^ getpid());
    if (args != 3)
    {
        Usage(argv[0]);
        exit(-1);
    }
    uint16_t port = atoi(argv[2]);
    std::string ip = argv[1];
    Sock client;
    int clientsock = client.CreateSocket();
    // 如果连接错误
    if (!client.Connect(clientsock, port, ip))
    {
        std::cerr << "Connect error" << std::endl;
        exit(2);
    }
    std::cout << "Connect success" << std::endl;

    bool quit = false;
    std::string buffer;
    // 向服务端传送任务
    while (!quit)
    {
        // 1.序列化
        Request req;
        std::cout << "please input # ";
        std::cin >> req._x >> req._op >> req._y;
        std::string tmp = req.Serialize(); // 进行序列化，以string的形式发送
        // 2.加上length
        std::string cal = Encode(tmp);
        Send(clientsock, cal);

        // 3.正常读取
        while (1)
        {
            // 获取消息
            bool flag = Recv(clientsock, &buffer); // 收到消息
            if (!flag)
            {
                quit = true;
                break;
            }
            // 解码 decode
            std::string package = Decode(buffer);
            if (package.empty())
                continue;
            Response resp;
            resp.Deserialize(package); // 通过rev向response内部输入数值 

            switch (resp._code)
            {
            case '1':
                std::cerr << "除零错误" << std::endl;
                break;
            case '2':
                std::cerr << "取余错误" << std::endl;
                break;
            case '3':
                std::cerr << "输入错误" << std::endl;
                break;
            default:
                std::cout << req._x << req._op << req._y << "=" << resp._res << "[success]" << std::endl;
                break;
            };
            break;
        }
    }
    return 0;
}